#!/bin/bash
# vim: set ft=sh

set -e -x

export GOPATH=$PWD/concourse
export PATH=$GOPATH/bin:$PATH

go install github.com/onsi/ginkgo/ginkgo

cd ${GOPATH}/src/github.com/concourse/baggageclaim

function permit_device_control() {
  local devices_mount_info=$(cat /proc/self/cgroup | grep devices)

  if [ -z "$devices_mount_info" ]; then
    # cgroups not set up; must not be in a container
    return
  fi

  local devices_subsytems=$(echo $devices_mount_info | cut -d: -f2)
  local devices_subdir=$(echo $devices_mount_info | cut -d: -f3)

  if [ "$devices_subdir" = "/" ]; then
    # we're in the root devices cgroup; must not be in a container
    return
  fi

  cgroup_dir=/tmp/devices-cgroup

  if [ ! -e ${cgroup_dir} ]; then
    # mount our container's devices subsystem somewhere
    mkdir ${cgroup_dir}
  fi

  if ! mountpoint -q ${cgroup_dir}; then
    if ! mount -t cgroup -o $devices_subsytems none ${cgroup_dir}; then
      return 1
    fi
  fi

  # permit our cgroup to do everything with all devices
  # ignore failure in case something has already done this; echo appears to
  # return EINVAL, possibly because devices this affects are already in use
  echo a > ${cgroup_dir}${devices_subdir}/devices.allow || true
}

function containers_gone_wild() {
  for i in $(seq 64 67); do
    mknod -m 0660 /dev/loop$i b 7 $i
  done
}

function salt_earth() {
  for i in $(seq 64 67); do
    losetup -d /dev/loop$i > /dev/null 2>&1 || true
  done
}

permit_device_control
containers_gone_wild
trap salt_earth EXIT

ginkgo -r -race -nodes 4 --failOnPending --randomizeAllSpecs --keepGoing "$@"
